package com.pignest.hotel.beans.global;

import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import com.pignest.framework.util.Log;
import com.pignest.hotel.beans.User;
import com.pignest.hotel.spring.Services;

public class ClientSession implements HttpSessionBindingListener {
	
	private String clientIP;
	private String userId;
	private WeakReference<User> user;
	private Date loginTime;
	private HashMap<String, Object> attributes;
	
	public ClientSession(User user) {
		this.userId = user.getId();
		this.user = new WeakReference<User>(user);
		this.loginTime = new Date();
	}
	
	public String getClientIP() {
		return clientIP;
	}
	
	public void setClientIP(String clientIP) {
		this.clientIP = clientIP;
	}
	
	public String getUserId() {
		return userId;
	}
	
	public String getUserName() {
		return getUser().getName();
	}
	
	public User getUser() {
		User u = user != null ? user.get() : null;
		if (u == null) {
			u = Services.getUserService().get(User.class, userId);
			this.user = new WeakReference<User>(u);
		}
		return u;
	}
	
	public boolean isLogined() {
		return user != null;
	}
	
	
	public void valueBound(HttpSessionBindingEvent arg0) {
		Log.e();
	}
	
	public void valueUnbound(HttpSessionBindingEvent arg0) {
		this.user = null;	//timeout
		Log.e();
	}
	
	public Date getLoginTime() {
		return loginTime;
	}
	
	public Object getAttribute(String key){
		return attributes == null ? null : attributes.get(key);
	}
	
	public void putAttribute(String key,Object value){
		if (attributes == null)
			attributes = new HashMap<String, Object>();
		attributes.put(key,value);
	}
	
	public void updateUser(User user) {
		this.user = new WeakReference<User>(user);
	}
	
	public void logout() {
		this.user = null;
		this.loginTime = null;
		this.clientIP = null;
		this.attributes = null;
	}
}
